<template>
  <el-row :gutter="10">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap>
        <el-tabs @tab-click="handleTabClick">
          <el-tab-pane :label="publicTabLabel" v-if="checkPermissions(['data:file:commonquery'])">
            <el-tree class="scrollbar" ref="treeRef" accordion v-loading="loading" :data="publicList"
              :props="defaultProps" @node-click="getformlist" node-key="id" :default-expanded-keys="expandedKey"
              :current-node-key="checkedKey" highlight-current="true">
              <template #default="{node,data}">
                <div style="display: flex; align-items: center">
                  <div style="margin-right: 10px"><img :src="data.imgType" alt="" /></div>
                  {{ data.name }}
                </div>
              </template>
            </el-tree>
          </el-tab-pane>
          <el-tab-pane :label="privateTabLabel">
            <el-select v-model="cityName" v-if="showcity" clearable
              placeholder="请选择" @change="getHandleChange">
              <el-option v-for="item in listName" :key="item.id" :label="item.divisionName" :value="item.divisionCode">
              </el-option>
            </el-select>
            <el-tree class="scrollbar" accordion v-loading="loading" :data="onlyList" :props="defaultProps"
              node-key="id" :default-expanded-keys="expandedKey1"
              :current-node-key="checkedKey1" highlight-current="true" @node-click="getonly">
              <template #default="{node,data}">
                <div style="display: flex; align-items: center">
                  <div style="margin-right: 10px"><img :src="data.imgType" alt="" /></div>
                  {{ data.name }}
                </div>
              </template>
            </el-tree>
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </el-col>

    <el-col :span="20" :xs="24">
      <!-- 右侧搜索 -->
      <ContentWrap>
        <el-tabs type="border-card" @tab-click="handleChangeTab">
          <el-tab-pane label="数据属性">
            <el-form v-if="trendsData.length > 0||showDataDowButton" :inline="true" label-width="auto">
              <el-form-item v-for="(item, index) in trendsData" :key="index" :label="item.description"
                style="margin-left: 10px;">
                <el-input style="width: 200px;" v-model="formInputs[index]" placeholder="请输入" />
              </el-form-item>
              <el-form-item v-if="trendsData.length > 0">
                <el-button type="primary" @click="query">查询</el-button>
                <el-button @click="eset">重置</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="dataDow" v-show="showDataDowButton&&checkPermissions(['data:file:commonquery'])" v-hasPermi="['data:file:dowShp']"
                  :loading="dataLoading">数据下载
                </el-button>
              </el-form-item>
            </el-form>
            <el-table :data="dataLiat" style="width: 100%" show-header>
              <el-table-column v-for="(item, index) in columns" :key="index" :prop="item.column_name"
                :label="item.description || item.column_name" min-width="150" show-overflow-tooltip>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <!-- <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="pageNo"
              :total="total"
              @pagination="getList"
            /> -->
            <div style="margin-top: 30px;">
              <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
                :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </div>
          </el-tab-pane>
          <el-dialog v-model="zipDialogVisible" title="数据下载" width="600">
            <el-form ref="ruleFormRef" :model="ruleForm2" :rules="rules2" label-width="auto" class="demo-ruleForm"
              :size="formSize" status-icon>
              <el-form-item label="数据范围:" prop="inputCode">
                (以下两种方式任选其一,下载编码为GBK)
              </el-form-item>
              <el-form-item label="按行政区选择:">
                <el-checkbox v-for="(item, index) in proForm" :key="index" v-model="checked1[index]"
                  :label="item.proName" size="large" @click="getChecked(item.longitude, item.latitude)" />
              </el-form-item>
              <el-form-item label="按经纬度范围:">
                <div>
                  <sapn>经度范围:</sapn>
                  <el-input v-model="dataForm.minx" maxlength="100"
                    style="width: 70px;margin-left: 10px;margin-right: 10px" placeholder="最小" />
                  至
                  <el-input v-model="dataForm.xmax" maxlength="100" style="width: 70px;margin-left: 10px"
                    placeholder="最大" />
                </div>
                <div>
                  <sapn>纬度范围:</sapn>
                  <el-input v-model="dataForm.miny" maxlength="100"
                    style="width: 70px;margin-left: 10px;margin-right: 10px" placeholder="最小" />
                  至
                  <el-input v-model="dataForm.ymax" maxlength="100" style="width: 70px;margin-left: 10px"
                    placeholder="最大" />
                </div>
              </el-form-item>

            </el-form>
            <template #footer>
              <div>
                <el-button type="primary" @click="confirmShp">确定</el-button>
                <el-button @click="closeShp">
                  关闭
                </el-button>
              </div>
            </template>
          </el-dialog>
          <el-tab-pane label="数据文件" v-if="ruleForm2.libraryTypes == 'proper'|| checkPermissions(['data:file:query'])">
            <div>
              <el-form-item v-if="!(!conceal&&activeName=='公共库')">
                <el-button type=" primary" @click="dupload" v-hasPermi="['basedic:basedic:upload']">
                  上传
                </el-button>
                <el-button @click="del" type="danger" v-hasPermi="['data:file:delete']">删除
                </el-button>
                <el-button type="primary" plain @click="downloads" :loading="loadings"
                  v-hasPermi="['data:file:zipDow']">下载
                </el-button>
              </el-form-item>
              <el-dialog v-model="dialogVisible" title="上传" width="620">
                <el-form ref="ruleFormRef" :model="ruleForm2" :rules="rules2" label-width="auto" class="demo-ruleForm"
                  status-icon>
                  <el-form-item label="数据范围：" prop="inputCode">
                    <el-select placeholder="请选择" v-model="ruleForm2.dataScope" style="width: 300px;">
                      <el-option v-for="item in dataAllOption" :value="item.divisionCode"
                        :label="item.divisionName"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="数据来源：" prop="source">
                    <el-input v-model="ruleForm2.dataSource" maxlength="100" style="width: 300px" placeholder="请输入"
                      show-word-limit type="textarea" />
                  </el-form-item>
                  <el-form-item label="图片上传" v-if="imgflag">
                    <el-upload ref="upload" class="upload-demo" :http-request="saveImageUpload" list-type="picture"
                      multiple="true" :show-file-list="false" :accept="PictureFormat">
                      <el-button type="primary">点击上传</el-button>
                    </el-upload>
                    <div><span>支持格式</span>{{ PictureFormat }}</div>
                  </el-form-item>
                  <el-form-item label="数据文件：">
                    <el-upload ref="upload" style="width: 300px" :auto-upload="false" class="upload-demo"
                      :show-file-list="true" :accept="ZipFormat" :limit="1" v-model:file-list="fileList" action="#"
                      :http-request="handleFileChange">
                      <el-button type="primary">选取文件</el-button>
                      <template v-if="showPercentage" #tip>
                        <el-progress :percentage="percentage" style="margin-top: 20px" />
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <div>
                    <el-button type="primary" @click="confirm(ruleFormRef)" :loading="isUploading || isMerging" :disabled="isUploading || isMerging">
                      <span v-if="isUploading">正在上传...</span>
                      <span v-else-if="isMerging">正在解析...</span>
                      <span v-else>确定</span>
                    </el-button>
<!--                    <el-button type="primary" @click="confirm((ruleFormRef))">-->
<!--                      <span v-if="isMerging">正在解析...</span>-->
<!--                      <span v-else>确定</span>-->
<!--                    </el-button>-->
                    <el-button @click="dialogVisibleClose()">
                      关闭
                    </el-button>
                  </div>
                </template>
              </el-dialog>
              <el-dialog v-model="matchFileVisible" title="匹配上传数据" :close-on-click-modal="false"
                :close-on-press-escape="false" width="550">
                <el-form class="demo-ruleForm">
                  <el-form-item label=" ">
                    <el-col :span="11" class="draggableClass">
                      <div class="draggable_title">读取文件的字段</div>
                      <draggable :list="shpFieldList" group="site" animation="300" dragClass="dragClass"
                        ghostClass="ghostClass" chosenClass="chosenClass" @start="onStart" @end="onEnd" :move="onMove">
                        <template #item="{ element }">
                          <div class="item pointer">
                            {{ element.fieldName }}
                          </div>
                        </template>
                      </draggable>
                      <span style="font-size: 12px;" class="pointer" @click="shpFieldListPush"> <el-icon>
                          <Plus />
                        </el-icon></span>
                    </el-col>
                    <el-col :span="1"></el-col>
                    <el-col :span="12" class="draggableClass">
                      <div class="draggable_title">数据库字段（固定）<span style="font-size: 11px; color: red;">*</span> <span
                          style="font-size: 11px; color: #ccc;">为必选字段</span></div>
                      <div v-for="(pot,index) in dbFieldList ">
                        <div style="font-size: 14px;font-weight: 500;">
                          <span v-show="pot.required" style="font-size: 12px; color: red;">*</span><span> {{
                            pot.fieldDesc
                            }}</span>-<span> {{
                            pot.fieldType
                            }}</span>
                        </div>
                      </div>
                    </el-col>
                  </el-form-item>

                  <el-form-item v-if='showPrompt'>
                    <div style="color: #e33f31;">请在页面点击“+”号，手动添加空值</div>
                  </el-form-item>

                </el-form>
                <template #footer>
                  <div>
                    <el-button type="primary" @click="matchFileconfirm(fieldMapdata)">确定
                    </el-button>
                    <el-button @click="matchFileVisible = false">
                      关闭
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </div>
            <div
              style=" display: flex; justify-content:space-between; background-color: #f5f8fa; padding: 16px 10px;border-radius: 10px">
              <div style="margin-top: 17px;margin-left: 7px;margin-right: -243px;">
                <el-icon color="#1692e0" size="20">
                  <Warning />
                </el-icon>
              </div>
              <div>
                <p style="margin: 0;font-size: 14px;color: #666666;">
                  需上传{{
                  formats
                  }}文件压缩包（zip格式）（至少包含{{ includes }}五个文件，且文件名称需相同）</p>
                <p style="margin: 0;font-size: 14px;color: #666666;">空间数据类型：{{
                  dataTypes
                  }}</p>
                <p style="margin: 0;font-size: 14px;color: #666666;">坐标系要求：WGS
                  84（EPSG:4326）或GCS_China_Geodetic_Coordinate_System_2000(EPSG:4490)</p>
              </div>
              <div>
                <div v-hasPermi="['basedic:basedic:temdownload']"
                  style="color: #2eb1e3;font-size: 14px;margin-right: 10px;text-decoration: underline;cursor: pointer;"
                  @click="TemplateDownload">模板下载
                </div>
                <div style="display: flex; align-items:center;margin-top: 20px;" @click="fieldDescribe">
                  <el-icon color="#ed1c24" size="20">
                    <Warning />
                  </el-icon>
                  <div style="font-weight: 700; color: #ed1c24;margin-left: 2px;">字段说明</div>
                </div>
                <el-dialog v-model="fieldDialogVisible" :show-close="false" width="800">
                  <template #header="{ close, titleId, titleClass }">
                    <div style="display: flex; align-items: center;justify-content: space-between">
                      <div>
                        <span style="font-size: 18px; font-weight: 700;">字段说明</span>
                        <span style="margin-left: 20px;">(上传文件属性的顺序、数据类型需与字段说明一致)</span>
                      </div>
                      <el-button type="primary" @click="close">
                        收起
                      </el-button>
                    </div>
                  </template>
                  <el-table :data="gridData" border header-cell-class-name="custom-header-top">
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column property="fieldType" label="字段类型" align='center' />
                    <el-table-column property="required" label="是否必填" align='center' />
                    <el-table-column property="fieldDesc" label="数据名称" align='center' />
                    <el-table-column property="remark" label="数据说明" align='center' />
                  </el-table>
                </el-dialog>
              </div>
            </div>
            <div style="margin-top: 30px">
              <el-table :data="tableData2" style="width: 100%" show-header @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="fileId" label="序号" width="55" />
                <el-table-column prop="dataScope" label="数据范围" width="150" />
                <el-table-column prop="fileNameOriginal" label="数据文件" width="200">
                  <template #default="scope">
                    <a target="_blank" class="no-underline">{{ scope.row.fileNameOriginal }}</a>
                  </template>
                </el-table-column>
                <el-table-column prop="dataSource" label="数据来源" />
                <el-table-column prop="imageUrl" label="图片展示" width="200" v-if="imgflag">
                  <template #default="scope">
                    <img :src='scope.row.imageUrl' style="max-width: 60px;"
                      @click="showImageDialog(scope.row.imageUrl)">
                  </template>
                </el-table-column>
                <el-table-column prop="userName" label="上传人" />
                <el-table-column prop="uploadTime" label="上传时间" width="200">
                  <template #default="scope">
                    <span>{{ formatDate(scope.row.uploadTime) }}</span>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="图片" width="150">
                  <template #default="scope">
                    <img :src="scope.row.imageUrl" alt="无" class="imageUrl" @click="downloadImage(scope.row.imageUrl)">
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
            <el-dialog v-model="dialogVisible2" width="700">
              <img :src='dialogImageUrl1' style="max-width: 100%;">
            </el-dialog>
            <div style="margin-top: 30px;">
              <el-pagination v-model:current-page="filePage.pageNo" v-model:page-size="filePage.pageSize"
                :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="filePage.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="使用设置" v-if="checkPermissions(['data:useconfig:query'])">
            <div style="margin-top: 30px;">
              <el-table :data="tableData3" ref="tableRef" border style="width: 100%;"
                :row-class-name="tableRowClassName" header-cell-class-name="custom-header">
                <el-table-column prop="name" label="数据名称" width="210" align="center">

                </el-table-column>
                <el-table-column prop="type" label="数据类型" width="210" align="center">
                  <template #default="scope">
                    <span v-if="scope.row.dataType === '1'">
                      点数据
                    </span>
                    <span v-else-if="scope.row.dataType === '2'">线数据</span>
                    <span v-else-if="scope.row.dataType === '3'">面数据</span>
                    <span v-else-if="scope.row.dataType === '4'">栅格数据</span>
                  </template>
                </el-table-column>
                <el-table-column label="数据使用设置" align="center">
                  <template #default="scope">
                    <template v-if="scope.row.dataType != 0">
                      <el-radio-group v-model="scope.row.libraryType" @change="handleChange(scope.row)">
                        <el-radio :value='1' size="large">公用库</el-radio>
                        <el-radio :value='2' size="large">专用库</el-radio>
                      </el-radio-group>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
              <!--              <p style="color:red;">按类型列出所有公用库数据（不包括不在前端展示的），默认设置为使用公用库，可修改设置。</p>-->
              <div style="display: flex; justify-content: center;">
                <el-button type="primary" @click="saveTableData">保存</el-button>
                <el-button @click="cancel">取消</el-button>
              </div>
            </div>
            <!-- <div style="margin-top: 30px;">
              <el-pagination v-model:current-page="filePage.pageNo"
                             v-model:page-size="filePage.pageSize"
                             :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled"
                             :background="background"
                             layout="total, sizes, prev, pager, next, jumper"
                             :total="filePage.total" @size-change="handleSizeChange"
                             @current-change="handleCurrentChange" />
            </div> -->
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup>
import {reactive, ref} from 'vue';
import { PictureFormat, PictureSize } from '@/utils/config'
import {ElFormItem, ElInput, ElButton, ElMessage, ElMessageBox} from 'element-plus';
import * as datarApi from "@/api/data";
import CryptoJS from 'crypto-js'
import {ZipFormat} from '@/utils/config'
import {generateUUID} from '@/utils'
import {handleTree} from '@/utils/tree'
import {forEach} from 'min-dash';
import {selectFileField} from '@/api/meta';
import download from '@/utils/download';
import {formatDate} from '@/utils/formatTime'
import * as dataApi from '@/api/data'
import draggable from "vuedraggable";
import moment from "moment/moment";
import {checkPermissions} from '@/utils/permissionsPlugin'
import * as userInfoApi from '@/api/login/index'
import {getUseSetList} from "@/api/data";
import { getSimpleGroupList } from '@/api/member/group';
import { useUserStore } from '@/store/modules/user'
const getUserInfo = useUserStore().getUserInfo
const flag = getUserInfo.roles.some(item => item.name =="省级管理员")
console.log(getUserInfo,'info');
const showLoading = ref(false)
//数据类型
const dataTypes = ref()
const formats = ref()
const includes = ref()
// 定义左侧表头数据
const publicTabLabel = '公共库';
const privateTabLabel = '专用库';
const showcity = ref(false)
const loading = ref(true) // 列表的加载中

//是否禁用
const checked1 = ref([false])
//数据下载
const showDataDowButton = ref(true)

const loadings = ref(false)
const dataLoading = ref(false)
const setKey = ref()
const treeId = ref();//设置默认选中
// 分页
const pageSize = ref('10')
const pageNo = ref('1')
const size = ref('default')
const disabled = ref(false)
const background = ref(false)
const total = ref()
const filePage = ref([]);
const activeName = ref(checkPermissions(['data:file:commonquery']) ? '公共库' : '专用库')
// 消息弹窗
const message = useMessage()
// 共用库数据
const publicList = ref([])
// 专用库数据
const onlyList = ref([])
// 对话框控制
const dialogVisible = ref(false)
const showloading = ref(false)
const zipDialogVisible = ref(false)
const tableData2 = ref([]) // 数据文件表格数据
const fileInput = ref(null)
// 左侧下拉菜单列表
const listName = ref([])
const cityName = ref('')
// 检索
const retrievalData = ref([])
// 文件列表
const fileList = ref([])
// 图片上传显示和隐藏
const imgflag = ref(true)
// 分片大小 1024 * 1024 = 1MB
const chunkSize = 1024 * 1024 * 10
const percentage = ref(0)
const showPercentage = ref(false)
// 字段提示
const showPrompt = ref(false)
// 分片上传正在合并时的提示
const isMerging = ref(false)
// 正在上传文件
const isUploading = ref(false)

// 按钮加载
const tableRowClassName = ({row}) => {
  if (row.type) {
    return ''
  }
  return 'warning-row'
}
const downloadImage = (imageUrl) => {
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = imageUrl;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
//左侧树状图图标
const iconList = ref([
  {type: '0', path: '/static/dataFileImage/folder.png'},
  {type: '1', path: '/static/dataFileImage/dit.png'},
  {type: '2', path: '/static/dataFileImage/wire.png'},
  {type: '3', path: '/static/dataFileImage/grid.png'},
  {type: '4', path: '/static/dataFileImage/face.png'},
])
// 字段列表
const gridData = ref([])
// 字段说明对话框
const fieldDialogVisible = ref(false)


// 初始化一个响应式对象来存储每个表单项的值，使用索引作为键
const formInputs = ref([]);

const defaultProps = {
  children: 'children',
  label: 'name',
}
const delRefresh = {
  treeId: '',
  libraryTypes: '',
  dbTableName: '',
  name: '',
  dataType: '',
}
const dataForm = reactive({
  minx: '',
  miny: '',
  xmax: '',
  ymax: ''
})
const radioData = ref([])
const handleChange = (row) => {
  radioData.value.push(row)
}

// 清空数据
const clearData = () => {
  dataLiat.value = [];
  pageNo.value = 1,
    pageSize.value = 10
  total.value = 0
  tableData2.value = []
  filePage.value = {
    pageNo: 1,
    pageSize: 10,
    total: 0
  }
}
// 获取左侧列表
// 默认展开
const expandedKey = ref([3])
const checkedKey = ref(9)
const checkNodeKey = ref({})

const expandedKey1 = ref([38])
const checkedKey1 = ref(71)
const checkNodeKey1 = ref({})
const treeRef = ref()
const conceal = ref(true)
const dictType = ref('')
const getDataList = async (divisionCode) => {
  try {
    const getUser = await userInfoApi.getInfo()
    console.log(JSON.stringify(getUser.user.divisionCode) + "user")
    if (getUser.user.divisionCode == 'root') {
      conceal.value = true
    } else {
      conceal.value = false
    }
    console.log("conceal:" + conceal.value)
    const response = await datarApi.getList(divisionCode)
    console.log(response,'---------');
    dictType.value = checkPermissions(['data:file:commonquery'])?response[0].dictType:response[1].dictType
    if (response.length > 0) {
      loading.value = false
      publicList.value = response[0].children
      publicList.value = response[0].children.flatMap(item => {  // 使用flatMap方法遍历response[0].children数组，并对每个元素执行指定的操作
        const typeImg = getTypeImg(item.dataType);  // 调用getTypeImg函数获取item的数据类型对应的图片
        const updatedItem = {...item, imgType: typeImg};  // 使用对象展开运算符创建一个新对象updatedItem，包含item的所有属性以及imgType属性
        if (item.children) {  // 如果item有children属性
          updatedItem.children = item.children.map(item2 => {  // 使用map方法遍历item.children数组，并对每个元素执行指定的操作
            const typeImg = getTypeImg(item2.dataType);  // 调用getTypeImg函数获取item2的数据类型对应的图片
            return {...item2, imgType: typeImg};  // 返回一个新对象，包含item2的所有属性以及imgType属性
          });
        }
        return updatedItem;  // 返回更新后的item
      });
      checkNodeKey.value = publicList.value[0].children[0]
      checkedKey.value = publicList.value[0].children[0].id;

      onlyList.value = response[1].children
      onlyList.value = response[1].children.flatMap(item => {  // 使用flatMap方法遍历response[0].children数组，并对每个元素执行指定的操作
        const typeImg = getTypeImg(item.dataType);  // 调用getTypeImg函数获取item的数据类型对应的图片
        const updatedItem = { ...item, imgType: typeImg };  // 使用对象展开运算符创建一个新对象updatedItem，包含item的所有属性以及imgType属性
        if (item.children) {  // 如果item有children属性
          updatedItem.children = item.children.map(item2 => {  // 使用map方法遍历item.children数组，并对每个元素执行指定的操作
            const typeImg = getTypeImg(item2.dataType);  // 调用getTypeImg函数获取item2的数据类型对应的图片
            return { ...item2, imgType: typeImg };  // 返回一个新对象，包含item2的所有属性以及imgType属性
          });
        }
        return updatedItem;  // 返回更新后的item
      });
      checkNodeKey1.value = onlyList.value[0].children[0]
      checkedKey1.value = onlyList.value[0].children[0].id;

      if (activeName.value == '公共库') {
        getformlist(checkNodeKey.value)
      }
      if (activeName.value == '专用库') {
        getonly(checkNodeKey1.value)
      }




    } else {
      loading.value = true
    }
  } catch (error) {
    loading.value = false
    console.log('失败');
    // 在这里处理异常
  }
}
const setLog = {
  cName: '',
  parentId: ''
}
const getimgFlag = ref('')
const dataTypeList = ref([
  {type: '1', name: '点', format: 'shp', include: 'dbf、prj、shp、shx、cpg'},
  {type: '2', name: '线', format: 'shp', include: 'dbf、prj、shp、shx、cpg'},
  {type: '3', name: '面', format: 'shp', include: 'dbf、prj、shp、shx、cpg'},
  {type: '4', name: '栅格', format: 'tif', include: 'tif、tif.ovr、tif.aux.xml、tif.xml、tfw'},
])
// 公共库
const getformlist = async (data) => {
  checkedKey.value = data.id;
  getimgFlag.value = data.id
  if (data.id == 68) {
    imgflag.value = true
  } else {
    imgflag.value = false
  }
  const typeName = getTypeName(data.dataType);
  dataTypes.value = typeName
  const f = getFormatName(data.dataType);
  formats.value = f
  const i = getIncludeName(data.dataType);
  includes.value = i
  showDataDowButton.value = true
  checkNodeKey.value = data
  // 切换时清空
  formInputs.value = []
  setLog.cName = data.name
  setLog.parentId = data.parentId
  getDataListFile(data.id, dictType.value)
  delRefresh.treeId = ''
  delRefresh.libraryTypes = ''
  delRefresh.dbTableName = ''
  delRefresh.name = ''
  delRefresh.dataType = ''
  ruleForm2.treeId = data.id
  if (data.children.length <= 0) {
    delRefresh.name = data.name
    delRefresh.treeId = data.id
    delRefresh.libraryTypes = dictType.value
    delRefresh.dbTableName = data.dbTableName
    delRefresh.dataType = data.dataType
    const pageList = {
      typeId: data.id,
      dbType: dictType.value,
      pageSize: pageSize.value,
      pageNo: pageNo.value
    }
    retrievalData.value = pageList
    try {
      let dataList = await datarApi.getPageList(pageList);
      // 更新表格列和数据
      columns.value = dataList.titleDec; // 如果需要动态更新列
      dataLiat.value = dataList.resData; // 更新数据
      trendsData.value = dataList.selectFieldDec; // 动态展示
      total.value = dataList.total; //总条数
      pageSize.value = dataList.pageSize; // 每页条数
      pageNo.value = dataList.pageNo; // 页
    } catch (error) {
      console.log('失败', error);
      // 在这里处理异常
    }
    pageSize.value = 10
    pageNo.value = 1
  }
}
// 专用库
const getonly = async (data) => {
  checkedKey1.value = data.id
  getimgFlag.value = data.id
  if (data.id == 101) {
    imgflag.value = true
  } else {
    imgflag.value = false
  }
  const typeName = getTypeName(data.dataType);
  dataTypes.value = typeName
  const f = getFormatName(data.dataType);
  formats.value = f
  const i = getIncludeName(data.dataType);
  includes.value = i
  showDataDowButton.value = false
  // 切换时清空
  formInputs.value = []
  setLog.cName = data.name
  setLog.parentId = data.parentId
  getDataListFile(data.id, 'proper')
  delRefresh.treeId = ''
  delRefresh.libraryTypes = ''
  delRefresh.dbTableName = ''
  delRefresh.name = ''
  delRefresh.dataType = ''
  ruleForm2.treeId = data.id
  if (data.children.length <= 0) {
    delRefresh.name = data.name
    delRefresh.treeId = data.id
    delRefresh.libraryTypes = 'proper'
    delRefresh.dbTableName = data.dbTableName
    delRefresh.dataType = data.dataType
    const pageList = {
      provinceCode: cityName.value,
      typeId: data.id,
      dbType: 'proper',
      pageSize: pageSize.value,
      pageNo: pageNo.value
    }
    retrievalData.value = pageList
    try {
      let dataList = await datarApi.getPageList(pageList);
      columns.value = dataList.titleDec; //表头
      dataLiat.value = dataList.resData; //数据
      trendsData.value = dataList.selectFieldDec; // 动态展示
      total.value = dataList.total; //总条数
      pageSize.value = dataList.pageSize; // 每页条数
      pageNo.value = dataList.pageNo; // 页
    } catch (error) {
      console.log('失败', error);
      // 在这里处理异常
    }
    pageSize.value = 10
    pageNo.value = 1
  }
}

const getTypeImg = (type) => {
  const icon = iconList.value.find((item) => item.type === type)
  return icon ? icon.path : null
}
const getTypeName = (type) => {
  const names = dataTypeList.value.find((item) => item.type === type)
  return names ? names.name : null
}
const getFormatName = (type) => {
  const names = dataTypeList.value.find((item) => item.type === type)
  return names ? names.format : null
}
const getIncludeName = (type) => {
  const names = dataTypeList.value.find((item) => item.type === type)
  return names ? names.include : null
}
// 数据属性
// 查询按钮
const query = async () => {
  // 假设formInputs.value和trendsData.value的长度相同
  // if (formInputs.value.length !== 0) {
    const newArray = formInputs.value.map((item, index) => ({selectValue: item}));
    const trendsDataArray = trendsData.value.map(item => ({
      dataType: item.dataType,
      columnName: item.columnName
    }));
    // 创建一个新数组，其中每个元素都是将newArray和trendsDataArray对应项合并后的对象
    const searchList = newArray.map((newItem, index) => ({
      ...newItem, // 包含selectValue
      ...trendsDataArray[index] // 合并dataType和columnName
    }));
    let pageList = retrievalData.value
    pageList.pageNo = 1
    pageList.searchList = searchList
    try {
      let dataList = await datarApi.getPageList(pageList);
      // 更新表格列和数据
      columns.value = dataList.titleDec; // 如果需要动态更新列
      dataLiat.value = dataList.resData; // 更新数据
      trendsData.value = dataList.selectFieldDec; // 动态展示
      total.value = dataList.total; //总条数
      pageSize.value = dataList.pageSize; // 每页条数
      pageNo.value = 1; // 页
    } catch (error) {
      console.log('失败', error);
      // 在这里处理异常
    }
  // }
};

// 重置按钮
const eset = () => {
  formInputs.value = [];
  query()
}
// 标题getimgFla
const columns = ref([])
// 标题数据属性表格
const dataLiat = ref([])
const trendsData = ref([])

const tableData3 = ref([]) //使用设置表格数据
// 数据文件表格
const getDataListFile = async (treeId, libraryTypes) => {
  if (checkPermissions(['data:file:query'])) {
    try {
      const response = await datarApi.getDataPage(treeId, libraryTypes)
      if (response.list.length > 0) {
        tableData2.value = response.list
        // 获取图片
        if (getimgFlag.value == 68 || getimgFlag.value == 101) {
          for (let i = 0; i < tableData2.value.length; i++) {
            const item = tableData2.value[i];
            if (item.imageUrl) {
              item.imageUrl = await getimgList(item.imageUrl)
            }
          }
        }
        filePage.value = response
      } else {
        tableData2.value = response.list
      }
    } catch (error) {
      clearData()
      // loading.value = false
      console.log('失败' + error);
      // 在这里处理异常
    }
  }
}
const getSetLists = async () => {
  if (checkPermissions(['data:useconfig:query'])) {
    try{
      const res = await datarApi.getUseSetList();
      if (res) {
        const allData = [];
        res.forEach(item => {
          allData.push(item);
          if (item.children) {
            allData.push(...item.children); // 添加子级数据
          }
        });
        tableData3.value = allData;
      }else{
        console.log('UsingSet Response is empty');
      }
    }catch{
      console.log('使用设置数据获取失败: ' + error);
    }
  }
}

// 获取图片
const getimgList = async (value) => {
  try {
    const imgUrl = await datarApi.getimgsList(value);
    const imgUrls = URL.createObjectURL(imgUrl);
    return imgUrls
  } catch {
    console.log('使用设置数据获取失败: ');
  }
}

const saveTableData = () => {
  ElMessageBox.confirm(
    '确认要设置吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'Warning',
    }
  ).then(async () => {
    try {
      if (radioData.value) {
        const data = radioData.value;
        // 转换数据
        const transformedData = data.map(item => ({
          dataId: item.id,
          libType: item.libraryType,
          name: item.name,
          dataType: item.dataType,
          tableName: item.dbTableName
        }));
        let useConfigResult = await dataApi.analysisSaveUseset(transformedData)

      // if (useConfigResult.data && useConfigResult.data>0) {
      //   radioData.value = []; // 清空选中数据
      //   getSetLists();
      //   ElMessage({type: 'success', message: '设置完成'})
      // } else {
      //   ElMessage({type: 'error', message: '设置失败'});
      // }
        radioData.value = []; // 清空选中数据
        getSetLists();
        ElMessage({
          type: 'info',
          message: '设置完成',
        })
      }
    }catch (error) {
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消设置',
    })
    radioData.value = [];
  })


}

const cancel = () =>{
  ElMessage({
    type: 'info',
    message: '已取消设置',
  })
  getSetLists()
}

const ruleFormRef = ref()
// 对话框数据
const ruleForm2 = reactive({
  dataScope: '',
  dataSource: '',
  file: '',
  libraryTypes: 'common',
  treeId: '',
})

const rules2 = reactive({
  dataScope: [
    {required: true, message: '不可为空', trigger: 'blur'},
  ],
  dataSource: [
    {required: true, message: '不可为空', trigger: 'blur'},
  ],

})
// 处理切换
// const handleTabClick =async (tab) => {
//   activeName.value = tab.props.label;
//   trendsData.value = []
//   columns.value = []
//   dataLiat.value = []
//   if (activeName == '公共库') {
//     ruleForm2.libraryTypes = 'common'
//     dictType.value = ruleForm2.libraryTypes
//     // conceal.value = 'common'
//     getformlist(checkNodeKey.value)
//   }else{
//     ruleForm2.libraryTypes = 'proper'
//     dictType.value = ruleForm2.libraryTypes
//     // conceal.value = 'proper'
//     await getcityList()
//     await getonly(checkNodeKey1.value)
//     // return
//   }
// };
const handleTabClick =async (tab) => {
  activeName.value = tab.props.label
  refresh()
};
// 刷新数据
const refresh = () => {
  if (activeName.value == '公共库') {
    getformlist(checkNodeKey.value)
  }
  if (activeName.value == '专用库') {
    console.log(checkNodeKey1.value,'====');
    getonly(checkNodeKey1.value)
  }
};
// 切换tab
const handleChangeTab = () => {
  refresh()
}
// 选取文件
const selectFile = () => {
  fileInput.value.value = ''
  // 触发隐藏的文件输入框点击事件
  fileInput.value.click();
  trendsData.value = []
  columns.value = []
  dataLiat.value = []
  if (tab.props.label == '公共库') {
    ruleForm2.libraryTypes = 'common'
  }
  if (tab.props.label == '专用库') {
    getCityList()
    ruleForm2.libraryTypes = 'proper'
  }
}
let formData = new FormData();
// 文件上传
const handleFileChange = async () => {
  const uploadFile = fileList.value[0]
  showLoading.value = true
  isUploading.value = true
  // 计算文件MD5
  let md5 = CryptoJS.MD5(
    uploadFile.raw.name + uploadFile.raw.size + 'zip' + uploadFile.raw.lastModified
  ).toString()
  let fileName = uploadFile.name
  uploadFile.md5 = md5
  const fileSize = uploadFile.size || 0
  let chunkTotals = Math.ceil(fileSize / chunkSize) // 计算分片总数量
  let percents = 0 //进度
  if (chunkTotals > 1) {
    // 分片导入
    showPercentage.value = true
    try {
      //分片上传前先校验
      let vResult = await dataApi.verifyFile({fileMD5: md5})
      // 循环上传分片
      for (let chunkNumber = vResult.hasChunkedNum, start = vResult.hasChunkedNum * chunkSize;
           chunkNumber < chunkTotals;
           chunkNumber++, start += chunkSize) {
        let end = Math.min(fileSize, start + chunkSize)
        const files = uploadFile.raw.slice(start, end)
        let form = new FormData()
        form.append('chunkNumber', chunkNumber + 1)
        form.append('chunkTotal', chunkTotals)
        form.append('fileName', fileName)
        form.append('file', files)
        form.append('fileMD5', md5)
        const result = await dataApi.uploadChunk(form)
        if (result.data) {
          // percents = percents + Number(((1 / chunkTotals) * 100).toFixed(2))
          percents = Math.round((chunkNumber / chunkTotals) * 100)
          console.log('--percents:--'+percents)
          if (chunkNumber == chunkTotals - 1) {
            percents = 100
          }
          uploadFile.percentage = percents
          percentage.value = percents
        }else{
          console.log('分片上传失败')
        }
      }
      // 开始合并文件时设置 isMerging 为 true
      isUploading.value = false
      isMerging.value = true
      let params = {
        fileMD5: md5,
        chunkTotal: chunkTotals,
        fileSize: uploadFile.size,
        ext: fileName.split('.').pop(),
        file: vResult.fileMD5,
        fileName: fileName,
        dataScope: ruleForm2.dataScope,
        dataSource: ruleForm2.dataSource,
        libraryTypes: ruleForm2.libraryTypes,
        treeId: ruleForm2.treeId,
        historyImgPath:imgListData.relativePath,
        historyImgToPngPath:imgListData.previewUrl,
      }
      // 分片合并，提交表单
      const result = await dataApi.merge(params)
      if (result.fileId) {
        ElMessage({type: 'success', message: '导入成功'})
        dialogVisible.value = false
        showloading.value = false
        //清空上传数据
        fileList.value = [];
        if (result.ifCheckFlag == 1) {
          //匹配文件数据
          setMatchFile(result)
        }
        getDataListFile(ruleForm2.treeId, ruleForm2.libraryTypes)
        dialogVisibleClose()
      } else {
        ElMessage({type: 'error', message: '导入失败'});
        showloading.value = false
      }
    } catch (error) {
      console.log(error)
    } finally {
      showLoading.value = false
      // 合并完成后设置 isMerging 为 false
      isMerging.value = false
      isUploading.value = false
    }
  } else if (chunkTotals == 1) {
    // 不分片导入
    try {
      isUploading.value = false
      isMerging.value = true
      let form = new FormData()
      form.append('file', uploadFile.raw)
      form.append('dataScope', ruleForm2.dataScope)
      form.append('dataSource', ruleForm2.dataSource)
      if (!conceal.value) {
        form.append('libraryTypes', 'proper')
      } else {
        form.append('libraryTypes', ruleForm2.libraryTypes)
      }
      form.append('treeId', ruleForm2.treeId)
      form.append('historyImgPath', imgListData.relativePath)
      form.append('historyImgToPngPath', imgListData.previewUrl)
      const result = await dataApi.confirm(form)
      if (result.fileId) {
        ElMessage({type: 'success', message: '导入成功'})
        dialogVisible.value = false
        showLoading.value = false
        if (result.ifCheckFlag == 1) {
          //匹配文件数据
          setMatchFile(result)
        }
        //清空上传数据
        fileList.value = [];
        if (!conceal.value) {
          getDataListFile(ruleForm2.treeId, 'proper')
        } else {
          getDataListFile(ruleForm2.treeId, ruleForm2.libraryTypes)
        }
        dialogVisibleClose()
      } else {
        showLoading.value = false
        isMerging.value = false
        isUploading.value = false
        ElMessage({type: 'error', message: '导入失败'})
      }
    } catch (error) {
      console.log(error)
    } finally {
      isMerging.value = false
      showLoading.value = false
    }
  }

}

// 确定
const confirm = async (formEl) => {
  if (!fileList.value.length) {
    ElMessage({
      type: 'error',
      message: '请选择上传文件'
    })
    return
  }
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleFileChange()
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 处理选中的值
const selectedFileId = ref([])
const handleSelectionChange = (selected) => {
  selectedFileId.value = selected;
}
// 上传
const dupload = () => {
  dialogVisible.value = true
  showloading.value = false
  showPercentage.value = false
  fileList.value = [];
  ruleForm2.dataScope = '';
  ruleForm2.dataSource = '';
  ruleForm2.file = '';
}

// 删除
const dIds = ref([])
const delIds = ref([])
const del = () => {
  var libraryTypes = ''
  var treeId = ''
  dIds.value = []
  delIds.value = []
  if (selectedFileId.value.length != 0) {
    libraryTypes = selectedFileId.value[0].libraryTypes
    treeId = selectedFileId.value[0].treeId
    forEach(selectedFileId.value, (item) => {
      if (selectedFileId.value.length >= 2) {
        dIds.value += item.fileId.toString() + ',';
        delIds.value = dIds.value.slice(0, -1)
      } else {
        delIds.value = item.fileId
      }
    })
    ElMessageBox.confirm(
      '是否确认删除数据文件编号为"' + delIds.value + '"的数据项?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'Warning',
      }
    ).then(async () => {
      try {
        await datarApi.delDataFile(delIds.value.toString(), libraryTypes, treeId, setLog.cName, setLog.parentId).then(() => {
          datarApi.delPublicData(delIds.value.toString(), delRefresh.dbTableName, libraryTypes,treeId).then(() => {
            getDataListFile(treeId, libraryTypes)
            ElMessage({
              type: 'success',
              message: '成功删除',
            });
            // refresh()
          })
        })
      } catch (error) {
        // 处理错误
        console.log(error + "删除异常");
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
  } else {
    ElMessage({
      type: 'error',
      message: '请选择要删除的数据文件',
    })
  }
}
// 左侧下拉城市列表
const getcityList = async () => {
  try {
    const response = await datarApi.cityList()
    if (response.length !== 0) {
      showcity.value = true
      listName.value = response?response:[]
    } else {
      loading.value = false
    }
  } catch (error) {
    loading.value = false
    console.log('失败');
    // 在这里处理异常
  }
}
//数据下载
const dataDow = async () => {
  zipDialogVisible.value = true
}
// 文件下载
const downloads = async () => {
  if (selectedFileId.value.length == 0) {
    ElMessage({
      type: 'error',
      message: '请选择要下载的数据文件',
    })
    loadings.value = false
    return
  }
  var zipPath = '';
  var libraryTypes = '';
  var dataScope = '';
  var name = '';
  selectedFileId.value.forEach(item => {
    libraryTypes = item.libraryTypes;
    dataScope = item.dataScope;
    if (selectedFileId.value.length >= 2) {
      zipPath += item.fileSite + ',';
      const randomNum = Math.floor(100000 + Math.random() * 900000)
      // 获取当前日期
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${day}`;showcity
      name = randomNum + '-' + formattedDate;
    } else {
      name = item.fileNameOriginal
      zipPath = item.fileSite
    }
  })
  try {
    loadings.value = true
    const responsePromise = await datarApi.getZipDow(zipPath, libraryTypes, setLog.cName, setLog.parentId, dataScope);
    if (responsePromise.size == 0) {
      ElMessage({
        type: 'error',
        message: '该数据文件文件不存在',
      })
      loadings.value = false
      return
    }
    download.zip(responsePromise, name);
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '详细错误，请查看数据操作日志',
    })
    loadings.value = false
  } finally {
    loadings.value = false
  }


}
const checkRef = reactive({
  longitude: '',
  latitude: ''
})
//数据下载
const confirmShp = async () => {
  if (checkRef.longitude && checkRef.latitude) {
    try {
      dataLoading.value = true
      const responsePromise = await datarApi.neiDowShp(checkRef.longitude, checkRef.latitude, delRefresh.dbTableName, delRefresh.dataType, delRefresh.name, setLog.parentId, delRefresh.libraryTypes);
      download.zip(responsePromise, delRefresh.name)
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '详细错误，请查看数据操作日志',
      })
      dataLoading.value = false
    } finally {
      dataLoading.value = false
    }
  } else {
    try {
      dataLoading.value = true
      const responsePromise = await datarApi.getShpDow(delRefresh.dataType, delRefresh.libraryTypes, delRefresh.dbTableName, delRefresh.name, dataForm.minx, dataForm.miny, dataForm.xmax, dataForm.ymax, setLog.parentId);
      download.zip(responsePromise, delRefresh.name)
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '详细错误，请查看数据操作日志',
      })
      dataLoading.value = false
    } finally {
      dataLoading.value = false
    }
  }
  zipDialogVisible.value = false
  dataForm.minx = ''
  dataForm.miny = ''
  dataForm.xmax = ''
  dataForm.ymax = ''
}
const closeShp = () => {
  zipDialogVisible.value = false
  dataForm.minx = ''
  dataForm.miny = ''
  dataForm.xmax = ''
  dataForm.ymax = ''
}
const proForm = ref()
const checkboxList = async () => {
  if (checkPermissions(['data:file:query'])) {
    // const pList = await datarApi.proList(null, null);
    const pList = await datarApi.newProList();
    proForm.value = pList
  } else {
    proForm.value = []
  }

}
const getChecked = async (item1, item2) => {
  checkRef.longitude = item1
  checkRef.latitude = item2
}
// 模板下载
const TemplateDownload = async () => {
  console.log('模板下载');
  try {
      const responsePromise = await datarApi.downTemplate(delRefresh.treeId);
      // 确认是Blob对象再下载
      if (responsePromise.type == 'application/json') {
        ElMessage({
            type: 'error',
            message: '此类型无对应模板',
        })
      } else {
          let fileName = delRefresh.name + '模板.zip'; // 默认文件名
          download.zip(responsePromise, fileName);
      }
    } catch (error) {
      console.log('模板下载error:'+error);
      ElMessage({
        type: 'error',
        message: '此类型无对应模板',
      })
    }
}


const close = () => {
  dialogVisible.value = false
}
// 关闭弹窗回调
const dialogVisibleClose = () => {
  showPercentage.value = false
  dialogVisible.value = false
  fileList.value = []
  percentage.value = 0
  ruleForm2.dataScope = ''
  ruleForm2.dataSource = ''
  // ruleForm2.treeId = ''
}

// 分页
const handleSizeChange = async (val) => {
  let pageList = retrievalData.value
  pageList.pageSize = val
  try {
    let dataList = await datarApi.getPageList(pageList);

    // 更新表格列和数据
    columns.value = dataList.titleDec; // 如果需要动态更新列
    dataLiat.value = dataList.resData; // 更新数据
    trendsData.value = dataList.selectFieldDec; // 动态展示
    total.value = dataList.total; //总条数
    pageSize.value = dataList.pageSize; // 每页条数
    pageNo.value = dataList.pageNo; // 页
  } catch (error) {
    console.log('失败', error);
    // 在这里处理异常
  }
};
const handleCurrentChange = async (val) => {
  let pageList = retrievalData.value
  pageList.pageNo = val
  try {
    let dataList = await datarApi.getPageList(pageList);
    // 更新表格列和数据
    columns.value = dataList.titleDec; // 如果需要动态更新列
    dataLiat.value = dataList.resData; // 更新数据
    trendsData.value = dataList.selectFieldDec; // 动态展示
    total.value = dataList.total; //总条数
    pageSize.value = dataList.pageSize; // 每页条数
    pageNo.value = dataList.pageNo; // 页
  } catch (error) {
    console.log('失败', error);
    // 在这里处理异常
  }
}
const dataAllOption = ref([]) // 数据范围
const getlistData = async () => {
  let data = await datarApi.getlistAllData()
  dataAllOption.value = data
}
//匹配上传数据
const fieldMapdata = ref({
  fileId: null,
  treeId: null,
  libraryTypes: "",
  /* 对应关系（key取dbFieldList 的值，value取shpFieldList的sortNum） */
  fieldMap: {},
  shpFieldList: [],
  dbFieldList: [],
})
const matchFileVisible = ref(false)
const drag = ref(false)
const setMatchFile = (result) => {
  showPrompt.value = false
  fieldMapdata.value = {...fieldMapdata.value, ...result};
  shpFieldList.value = result.shpFieldList
  //初始化shpFieldList数据方便储存时传参数
  reshpFieldList.value = result.shpFieldList
  //匹配数据库添加list 方便前端渲染
  result.dbFieldList.forEach(item => {
    item.list = []
  })
  dbFieldList.value = result.dbFieldList
  let obj = {};
  dbFieldList.value.forEach((item, index) => {
    obj[item.fieldName] = index;
  })
  result.fieldMap = {...obj}
  matchFileVisible.value = true
}
//临时储存修改数据
const redbFieldList = ref();
const reshpFieldList = ref()
const shpFieldList = ref([
  {sortNum: 1, fieldName: '数据1'},
  {sortNum: 2, fieldName: '数据2'},
  {sortNum: 3, fieldName: '数据3'},
  {sortNum: 4, fieldName: '数据4'},
  {sortNum: 5, fieldName: '数据5'},
  {sortNum: 6, fieldName: '数据6'},
  {sortNum: 7, fieldName: '数据7'},
  {sortNum: 8, fieldName: '数据8'},
  {sortNum: 9, fieldName: '数据9'},
])
const dbFieldList = ref(
  [
    {sortNum: null, fieldName: 'geom', list: []},
    {sortNum: null, fieldName: 'f_code_des', list: []},
    {sortNum: null, fieldName: 'soc', list: []},
    {sortNum: null, fieldName: 'code', list: []},
    {sortNum: null, fieldName: 'name', list: []},
    {sortNum: null, fieldName: 'name_pinyin', list: []},
    {sortNum: null, fieldName: 'mc', list: []},
  ]
)
const onStart = (node, ev) => {
  drag.value = true;
}
//拖拽结束事件
const onEnd = (node, ev) => {
  drag.value = false;
}
//关闭匹配数据弹窗
const matchFileClose = () => {
  matchFileVisible.value = false;
  shpFieldList.value = [];
  dbFieldList.value = []

}
//关闭匹配数据弹窗
const shpFieldListPush = () => {
  shpFieldList.value.push({
    sortNum: -1, fieldName: '空',
  })
}
const matchFileloding = ref(false)
// 确定
const matchFileconfirm = async (formEl) => {
  fieldMapdata.value
  if (shpFieldList.value.length < dbFieldList.value.length) {
    showPrompt.value = true
    ElMessage({
      type: 'warning',
      message: `“与数据库字段数不匹配”`,
    })
    return
  }
  let obj = {}, arr = [], fieldMap = {};
  //遍历服务端字段
  dbFieldList.value.forEach((item, index) => {
    obj[item.fieldName] = shpFieldList.value[index].sortNum;
  })
  formEl.fieldMap = {...obj}
  formEl.shpFieldList = shpFieldList.value;
  formEl.dbFieldList = dbFieldList.value;
  matchFileloding.value = true;
  const loading = ElLoading.service({
    lock: true,
    text: '数据匹配中......',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const data = await dataApi.analysisShpFile(formEl)
  if (data > 0) {
    loading.close()
    ElMessage({
      type: 'success',
      message: `导入成功,成功${data}条`,
    })
    getDataListFile(formEl.treeId, formEl.libraryTypes)
    // getPageList()
  } else {
    loading.close()
    ElMessage({
      type: 'error',
      message: '导入失败',
    })
  }
  matchFileClose()

}
//当插入、移除、改变位置时会触发该事件
const onSortB = (e) => {
  let data = [];
  dbFieldList.value.forEach((item, index) => {
    if (item.list.length > 0) {
      item.sortNum = item.list[0].sortNum;
    }
  })
  redbFieldList.value = dbFieldList.value;



};

const onMove = (e, originalEvent) => {
  // 不允许停靠到A组的第一个元素
  // if (e.relatedContext.list.length==1) {
  //   e.relatedContext.list=[e.draggedContext.element]
  //   ElMessage({
  //       type: 'info',
  //       message: '当前数据以添加',
  //     })
  //   return false;
  // }
  return true;
};
// 图片上传数据
const imgListData = reactive({
  relativePath: '',
  previewUrl: '',
})
const saveImageUpload = async (content) => {
  let form = new FormData()
  form.append('file', content.file)
  const data = await dataApi.uploadImage(form)
  if (data.data) {
    ElMessage.success('上传成功!')
    imgListData.relativePath = data.data.relativePath
    imgListData.previewUrl = data.data.previewUrl
  } else {
    ElMessage.error('上传失败!')
  }
}
const dialogImageUrl1 = ref()
const dialogVisible2 = ref(false)
// 图片放大展示
const showImageDialog = (imageUrl) => {
  dialogVisible2.value = true;
  dialogImageUrl1.value = imageUrl;
}

// 字段说明
const fieldDescribe = async () => {
  fieldDialogVisible.value = true
  let describes = {
    treeId: ruleForm2.treeId,
    provinceCode: cityName.value
  }
  try {
    let dataList = await datarApi.getdescribeList(describes);
    if (dataList.length > 0) {
      gridData.value = dataList
    }
  } catch (error) {
    console.log('失败', error);
    // 在这里处理异常
  }
}

const getHandleChange = async (Value) => {
  console.log(Value,'------------');
  getDataList(Value)
  // const pageList = {
  //   provinceCode: Value,
  //   typeId: getimgFlag.value,
  //   dbType: 'proper',
  //   pageSize: pageSize.value,
  //   pageNo: pageNo.value
  // }
  // try {
  //   let dataList = await datarApi.getPageList(pageList);
  //   // 更新表格列和数据
  //   columns.value = dataList.titleDec; // 如果需要动态更新列
  //   dataLiat.value = dataList.resData; // 更新数据
  //   trendsData.value = dataList.selectFieldDec; // 动态展示
  //   total.value = dataList.total; //总条数
  //   pageSize.value = dataList.pageSize; // 每页条数
  //   pageNo.value = 1; // 页
  // } catch (error) {
  //   console.log('失败', error);
  //   // 在这里处理异常
  // }
}
onMounted(async () => {
  getDataList('')
  getDataListFile('', '')
  getSetLists()
  checkboxList()
  getlistData()
})
</script>

<style lang="scss" scoped>
:deep(.custom-header) {
   background-color: #3560f6 !important;
   /* 设置表头背景色 */
   color: #ffffff !important;
   /* 设置表头文字颜色 */
   font-weight: bold !important;
   /* 设置表头文字加粗 */
   height: 42px;
}
:deep(.custom-header-top) {
  background-color: #e5ebf7 !important;
  color: #000;
  font-size: 14px;
}
.text-center {
  text-align: center;
}

.demo-tab {
  height: 100vh;
}

.el-table .warning-row {
  background-color: rgb(112, 192, 246);
  font-weight: 700;
}

.no-underline {
  text-decoration: none;
  color: blue;
}


.imageUrl {
  width: 100%;
  height: auto;
}

.imageUrl:hover {
  cursor: pointer;
}

/* ::v-deep .el-table td,
.el-table th.is-leaf {
    border-bottom: none;
} */
:deep(.el-progress__bar) {
  flex: 1;
}

:deep(.el-progress__text) {
  width: 40px;
  text-align: right;
  min-width: 0;
}

.scrollbar {
  max-width: 200px;
  max-height: calc(100vh - 205px);
  overflow-y: auto;
  /* 滚动条整体样式 */
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: #8ABEF4 #f1f1f1; /* Firefox */

  /* WebKit 浏览器（Chrome, Safari） */
  &::-webkit-scrollbar {
    width: 8px; /* 滚动条宽度 */
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1; /* 轨道背景颜色 */
  }

  &::-webkit-scrollbar-thumb {
    background: #ccc; /* 滚动条拇指颜色 */
    border-radius: 6px; /* 滚动条拇指圆角 */
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #ccc; /* 滚动条拇指悬停颜色 */
  }
}

.draggableClass {
  padding: 0 10px;
  border: 1px solid #3322120f;
  height: 400px;
  overflow: auto;

  .draggable_title {
    color: #000;
    font-weight: 500;
    margin-bottom: 5px;
  }

  .item {
    font-size: 12px;
    font-weight: 400;
  }

  &::-webkit-scrollbar, .webkitScrollbar::-webkit-scrollbar {
    width: 5px; /* 滚动条宽度 */
  }

  /* 滚动条滑块部分 */
  &::-webkit-scrollbar-thumb, .webkitScrollbar::-webkit-scrollbar-thumb {
    background-color: #D7DBDE; /* 滑块颜色 */
    border-radius: 5px; /* 滑块圆角 */
  }

  /* 滚动条轨道部分 */
  &::-webkit-scrollbar-track, .webkitScrollbar::-webkit-scrollbar-track {
    background-color: #fff; /* 轨道颜色 */
    border-radius: 2px; /* 轨道圆角 */
  }
}
</style>
